import os
import sys
import getopt
import ma.utils.location
from ma.utils.clustersetup import CLUSTER_IPS


MAX_TRIES = 20


def execute_till_success(cmd):
    ret = 1
    tries = 0
    while ret != 0 and tries < MAX_TRIES:
        ret = os.system(cmd)
        tries = tries + 1
    
    return ret


def sync_time():
    url_atomic_time = 'time-a.nist.gov'

    print 'Make a copy for the localtime file'
    if execute_till_success('mv /etc/localtime /etc/localtime-old') != 0:
        print('Failed at making copy for the localtime file')
        return False
    
    print 'Make a soft-link to the UTC file'
    if execute_till_success('ln -sf /usr/share/zoneinfo/UTC /etc/localtime') != 0:
        print('Failed at making soft-link to the UTC file')
        return False
    
    print 'Synchronize with ' + url_atomic_time
    if execute_till_success('rdate -s ' + url_atomic_time) != 0:
        print('Failed at synchronizing with ' + url_atomic_time)
        return False
    
    print 'Write to the sysconfig/clock'
    #fd = open('/etc/sysconfig/clock', 'w+')
    #fd.write('ZONE="Asia/Karachi"\nUTC=true\nARC=false')
    #fd.close()
    
    print 'Set the hardware clock'
    if execute_till_success('/sbin/hwclock --systohc') != 0:
        print('Failed at setting the the hardware clock')
        return False
    
    return True


print('usage: python synctime.py [-r to start on all remote machines]')

# sync time locally
sync_time()

start_remote = False
optlist, args = getopt.getopt(sys.argv[1:], 'r')
for opt in optlist:
    if opt[0] == '-r':
        start_remote = True

python_exec_path = ma.const.XmlData.get_filepath_str_data(ma.const.xml_python_exec)
sync_exec_path = python_exec_path + ' ' + os.path.join(ma.utils.location.get_scripts_path(), 'synctime.py')

if start_remote:
    for ip in CLUSTER_IPS:
        os.system('ssh ' + ip + ' ' + sync_exec_path)
        print("Synced time with atomic clock at " + ip)
        
